package com.itheima.Wuziqi.service;

/**
 * 五子棋规则实现
 */
public class GobangRule implements GameRule {
    private int boardSize;
    
    public GobangRule(int boardSize) {
        this.boardSize = boardSize;
    }
    
    @Override
    public boolean isValidMove(int[][] board, int row, int col) {
        // 检查是否在棋盘范围内且为空位
        return row >= 0 && row < boardSize && col >= 0 && col < boardSize && board[row][col] == 0;
    }
    
    @Override
    public boolean checkWin(int[][] board, int row, int col, int player) {
        // 检查四个方向：水平、垂直、两个对角线
        int[][] directions = {{0, 1}, {1, 0}, {1, 1}, {1, -1}};
        
        for (int[] dir : directions) {
            int count = 1; // 当前位置已有一个棋子
            
            // 正方向检查
            for (int i = 1; i <= 4; i++) {
                int r = row + i * dir[0];
                int c = col + i * dir[1];
                if (r >= 0 && r < boardSize && c >= 0 && c < boardSize && board[r][c] == player) {
                    count++;
                } else {
                    break;
                }
            }
            
            // 反方向检查
            for (int i = 1; i <= 4; i++) {
                int r = row - i * dir[0];
                int c = col - i * dir[1];
                if (r >= 0 && r < boardSize && c >= 0 && c < boardSize && board[r][c] == player) {
                    count++;
                } else {
                    break;
                }
            }
            
            // 五子连珠
            if (count >= 5) {
                return true;
            }
        }
        
        return false;
    }
    
    @Override
    public boolean checkDraw(int[][] board) {
        // 检查棋盘是否已满
        for (int i = 0; i < boardSize; i++) {
            for (int j = 0; j < boardSize; j++) {
                if (board[i][j] == 0) {
                    return false; // 还有空位，不是平局
                }
            }
        }
        return true; // 棋盘已满，平局
    }
}
    